package com.algorithm.learning.base;

/**
 * @program: algorithm-learning
 * @description:
 * @author: YuKai Fan
 * @create: 2024/8/19 22:24
 **/
public class 二分法 {

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int num = 2;
        System.out.println(binarySearchFirstPos(arr, num));
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            }
            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (arr[left] == target) {
            return left;
        }
        return -1;
    }

    public static int binarySearchFirstPos(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (target > arr[mid]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        if (arr[left] == target) {
            return left;
        }
        return -1;
    }
}
